#include <iostream>
#include <unistd.h>	//sleep()
#include <string.h>	//strlen()
#include <fcntl.h>	//O_WRONLY O_RDONLY
#include <pthread.h>
#include <sys/types.h>
#include <sys/stat.h>	//mkfifo()
#include <errno.h>	//EEXIST

#define FIFOPATH1 "/home/xbq/dev/test/thread/fifo1"
#define FIFOPATH2 "/home/xbq/dev/test/thread/fifo2"
#define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)

using namespace std;

void* thread1 (void*)
{
	int readfd, writefd;
	char* buff = (char*)"nihao thread!";
	char* recvbuff;
	recvbuff = new char[15];
	writefd = open(FIFOPATH1, O_WRONLY);
	if (writefd < 0)
	{
		cout << "error: ";
		perror("open failed!");
	}
	readfd = open(FIFOPATH2, O_RDONLY);
	if (readfd < 0)
	{
		cout << "error: ";
		perror("open failed!");
	}
	
	string str;
	while (true)
	{
		cin >> str;
		int len = str.length();
		write(writefd, str.c_str(), len);
		read(readfd, recvbuff, 15);
		cout << __LINE__ << ":" << recvbuff << "in thread1" << endl;
	}
	delete recvbuff;
	close(readfd);
	close(writefd);
}

void* thread2 (void*)
{
	int readfd, writefd, n;
	char* buff;
	buff = new char[15];
	readfd = open(FIFOPATH1, O_RDONLY);
	writefd = open(FIFOPATH2, O_WRONLY);

	while (true)
	{
		read(readfd, buff, 13);
		sprintf(buff, "%s%s", buff, "!!");
		//cout << __LINE__ << ":" << buff << "in thread2" << endl;
		//cout << sleep(5);
		write(writefd, buff, strlen(buff));
	}
	delete buff;
	close(readfd);
	close(writefd);
}

int main (void)
{
	pthread_t tid1, tid2;
	mkfifo(FIFOPATH1, FILE_MODE);
	mkfifo(FIFOPATH2, FILE_MODE);
	cout << sizeof(long) << " " << sizeof(short) << endl;

	pthread_create(&tid1, NULL, thread1, NULL);
	pthread_create(&tid2, NULL, thread2, NULL);
	pthread_join(tid1, 0);
	pthread_join(tid2, 0);
	unlink(FIFOPATH1);
	unlink(FIFOPATH2);
	return 0;
}

